<template>
  <PageWrapper class="high-form" title="采样计划">
    <CollapseContainer title="基础信息">
      <BasicForm @register="registerForm" ref="formRef">
        <template #checkSpot>
          <a-button type="primary" @click="handleShowSpot"> 点位个数频次周期参考表 </a-button>
          <checkSpotModal @register="registerModal1" />
        </template>


        <template #detailList="{ model }">
          <BasicTable @register="registerTable" :dataSource="model.detailList">
            <template #toolbar>
              <a-button @click="handleExport"> 导出</a-button>
              <a-button type="primary" @click="handleShowItem"> 新增</a-button>
            </template>
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'action'">
                <TableAction :actions="[
                  // {
                  //   tooltip: '复制',
                  //   icon: 'ant-design:copy-outlined',
                  //   onClick: handleCopy.bind(null, record),
                  // },
                  {
                    tooltip: '修改',
                    icon: 'clarity:note-edit-line',
                    onClick: handleEdit.bind(null, record),
                  },
                  {
                    tooltip: '删除',
                    icon: 'ant-design:delete-outlined',
                    color: 'error',
                    onClick: (e) => { e.stopPropagation(); },
                    popConfirm: {
                      title: '是否确认删除',
                      confirm: handleDelete.bind(null, record),
                      placement: 'left'
                    },
                  },
                ]" />
              </template>
            </template>
          </BasicTable>
          <formModal @register="registerModal" @success="handleSuccess" />
          <checkItemModal @register="registerModal2" @success="handleSuccess" />
        </template>
      </BasicForm>
    </CollapseContainer>

    <CollapseContainer title="流程信息">
      <SelectApprover :id="id" :type="type" @success="getFlowData" />
    </CollapseContainer>

    <a-button type="primary" @click="handleSubmitForm" v-if="serverData.showCommit"> 提交 </a-button> <span> </span>
    <a-button type="primary" @click="handleSaveForm(0)" v-if="serverData.showCommit"> 存草稿 </a-button> <span> </span>
    <a-button color="error"  @click="handleDeleteForm" v-if="serverData.showCommit && id>0"> 删除 </a-button>

  </PageWrapper>
</template>

<script lang="ts">
import { defineComponent, ref, onBeforeMount, onMounted, } from 'vue';
import { Button, Tag } from 'ant-design-vue';
import { BasicForm, useForm, ApiSelect } from '/@/components/Form/index';
import { PageWrapper } from '/@/components/Page';
import { CollapseContainer } from '/@/components/Container';
import { useMessage } from '/@/hooks/web/useMessage';
import { useRoute, useRouter } from 'vue-router'
import { cloneDeep } from 'lodash-es';
import { BasicTable, useTable, TableAction, } from '/@/components/Table';
import { useModal } from '/@/components/Modal';

import { formSchema } from './data';
import SelectApprover from '/@/views/process/SelectApprover.vue';
import { businessdata } from '/@/api/work/work';
import formModal from './formModal.vue';
import checkSpotModal from './checkSpotModal.vue';
import checkItemModal from './checkItemModal.vue';
import { add, update, del as delPlan } from '/@/api/project/plan';
import { add as addDetail, del, } from '/@/api/project/planDetail';


export default defineComponent({
  components: {
    formModal, BasicTable, TableAction, BasicForm, CollapseContainer, PageWrapper, Button, Tag,
    ApiSelect, SelectApprover, checkSpotModal, checkItemModal
  },
  emits: ['success', 'register'],
  setup() {
    //主表单
    const [registerForm, { setFieldsValue, validate }] = useForm({
      schemas: formSchema,
      labelWidth: 150,
      showActionButtonGroup: false,
    });

    //流程参数 begin
    const serverDataType: any = { showApprove: false, aaList: [], ccList: [] }
    const serverData = ref(serverDataType);
    const id = ref(0);
    const type = ref('CheckPlan');
    function getFlowData(returnData: any) {
      serverData.value = returnData
    }
    //流程参数 end

    onBeforeMount(() => {
      // 获取路由参数
      const r = useRoute();
      let idStr = r.params.id
      if (typeof (idStr) == 'string') {
        id.value = parseInt(idStr, 10)
      } else {
        id.value = parseInt(idStr[0], 10)
      }
    })

    onMounted(() => {
      flushData()
    })

    const flushData = () => {
      if (id.value > 0) {
        setFieldsValue(serverData)
        businessdata({ id: id.value, type: type.value }).then(res => {
          res.projectType = res.projectType.split(',')
          setFieldsValue(res)
          console.log('获取【采样计划】数据成功', res)
        })
      }
    }
    //获取检测点位


    //采样信息列表
    const [registerTable] = useTable({
      columns: [{
        title: '操作',
        dataIndex: 'action',
      }, {
        title: '检测类别',
        dataIndex: 'checkType',
      }, {
        title: '检测点位',
        dataIndex: 'checkSpot',
      }, {
        title: '项目',
        dataIndex: 'checkItem',
      }, {
        title: '类别',
        dataIndex: 'checkSubtype',
      }, {
        title: '检测方法',
        dataIndex: 'checkStandard',
      }, {
        title: '采集或保存方法',
        dataIndex: 'collectWay',
      }, {
        title: '点位(个)',
        dataIndex: 'checkSpotCount',
      }, {
        title: '频次(次)',
        dataIndex: 'checkFreq',
      }, {
        title: '周期(天)',
        dataIndex: 'checkCycle',
      }, {
        title: '采样时间',
        dataIndex: 'checkTime',
      }, {
        title: '检测项目总数',
        dataIndex: 'checkItemCount',
      }, {
        title: '分析费',
        dataIndex: 'checkPrice',
      }, {
        title: '采样费单价',
        dataIndex: 'collectPrice',
      }, {
        title: '测试费小计',
        dataIndex: 'checkFee',
      },],
      formConfig: {
        labelWidth: 120,
        showAdvancedButton: false,
        showResetButton: false,
        autoSubmitOnEnter: true,
      },
      canColDrag: true,
      useSearchForm: false,
      bordered: true,
      showIndexColumn: true,
    });


    //采样点位弹框
    const [registerModal1, { openModal: openModal1 }] = useModal();
    function handleShowSpot() {
      openModal1(true, {
      });
    }

    //采样信息新增：表格弹框
    const [registerModal2, { openModal: openModal2 }] = useModal();
    function handleShowItem() {
      if (id.value > 0) {
        openModal2(true, {
          planId: id.value,
        });
      } else {
        createMessage.error('请先点击下方"存草稿"按钮，保存采样计划，然后添加采样信息');
      }
    }
    //导出
    function handleExport() {
      if (process.env.NODE_ENV === 'production') {
        location.href = '/CheckPlanDetail/export/' + id.value;
      } else {
        location.href = '/check-api/CheckPlanDetail/export/' + id.value;
      }
    }

    //采样信息编辑：弹框
    const [registerModal, { openModal }] = useModal();
    function handleCreate() {
      openModal(true, {
        planId: id.value,
        isUpdate: false,
      });
    }
    function handleEdit(record: Recordable) {
      openModal(true, {
        record,
        isUpdate: true,
      });
    }
    function handleCopy(record: Recordable) {
      const data = cloneDeep(record) || {};
      data.id = null; // 重置ID
      addDetail(data).then(() => {
        createMessage.success('复制成功');
        flushData();
      });
    }
    function handleDelete(record: Recordable) {
      del(record.id).then(() => {
        flushData();
      });
    }
    function handleSuccess() {
      setTimeout(() => {
        flushData();
      }, 200);
    }

    const { createMessage } = useMessage();
    const router = useRouter();
    //提交，需要选择审批人
    async function handleSubmitForm() {
      if (serverData.value.aaList == null || serverData.value.aaList.length == 0) {
        createMessage.success({
          content: '请选择审批人',
          duration: 1,
        });
        return
      }
      handleSaveForm(1)
      router.push('/work/work-done');//跳转已处理
    }
    async function handleSaveForm(type) {
      let content = '存草稿成功'
      const values = await validate();
      if (type === 1) {
        content = '提交成功'
        values['aaList'] = serverData.value.aaList
        values['ccList'] = serverData.value.ccList
      }
      console.log('formData=', values)
      values.projectType = values.projectType.join(',')

      if (id.value > 0) {
        await update(values);
      } else {
        await add(values).then(res => {
          //跳转查看页
          router.push('/project/plan/view/' + res.id);
        });
      }
      createMessage.success({
        content: content,
        duration: 1,
      });
      flushData();
    }
     //删除
    function handleDeleteForm(){
        if(confirm("确认要删除吗")){
            delPlan(id.value).then(res=>{
               router.push('/work/work-done');
            });
        }
    }


    return {
      registerModal1, handleShowSpot,
      registerModal2, handleShowItem, handleExport,
      registerForm, handleSaveForm, handleSubmitForm, handleDeleteForm,
      registerModal, registerTable, handleCreate, handleEdit, handleDelete, handleSuccess, handleCopy,
      getFlowData, serverData, id, type
    };
  },
});
</script>
